package com.pet.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pet.mapper.UserMapper;
import com.pet.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(User user) {
        //根据用户名查询数据库
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",user.getUsername());
        User user1 = userMapper.selectOne(queryWrapper);
        if(user1 == null) return "用户名不存在";
        //用户名存在的情况下，对比密码是否一致
        String password = user.getPassword();
        byte[] passByte = password.getBytes();
        String md5Pass = DigestUtils.md5DigestAsHex(passByte);
        if(!user1.getPassword().equals(md5Pass)) return "密码不正确";
        //如果程序执行到这一行，则数据用户的输入正确的，返回token
        String token = UUID.randomUUID().toString().replace("-", "");
        return token;
    }

    @Override
    public Boolean register(User user) {
        //将密码进行md5加密
        String password = user.getPassword();
        byte[] passByte = password.getBytes();
        String md5Pass = DigestUtils.md5DigestAsHex(passByte);
        //根据用户名查询数据库的条件选择器
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername());
        //查询数据库是否有此用户名的记录
        User user1 = userMapper.selectOne(userQueryWrapper);
        if(user1 != null) return false;
        user.setPassword(md5Pass);
        //插入用户记录
        int flag = userMapper.insert(user);
        if(flag == 0) return false;
        return true;
    }
}
